
package com.rt.schedulenew.service.impl;

import com.rt.schedulebase.dto.DictExamQueueDto;
import com.rt.schedulebase.dto.DictScheduleApmDto;
import com.rt.schedulebase.entity.DictScheduleApmDuty;
import com.rt.schedulebase.mapper.DictScheduleApmMapper;
import com.rt.schedulenew.api.IDeptDutyService;
import com.rt.schedulenew.api.IDictScheduleApmDutyService;
import com.rt.schedulenew.dto.DictScheduleApmDutyDto;
import com.rt.schedulenew.utils.base.CommonUtil;
import com.rt.schedulenew.utils.global.JsonResult;
import com.rt.schedulenew.utils.global.JsonResultUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class DeptDutyImpl implements IDeptDutyService {
    @Autowired
    private DictExamQueueServiceImpl dictExamQueueService;
    @Autowired
    private DictScheduleApmMapper dictScheduleApmMapper;
    @Autowired
    private IDictScheduleApmDutyService dictScheduleApmDutyService;



    /**
     * 获取人员排班
     * @param dto
     * @return
     */
    @Override
    public JsonResult getDutyList(DictScheduleApmDutyDto dto) {
        // 获取检查类别的可用队列
        DictExamQueueDto dictExamQueueDto = new DictExamQueueDto();
        dictExamQueueDto.setClassAttr(dto.getClassAttr());
        dictExamQueueDto.setExamClassList(CommonUtil.split2List(dto.getExamClass()));
        List<DictExamQueueDto> queues = dictExamQueueService.getQueueList(dictExamQueueDto);

        // 获取队列的时段列表
        DictScheduleApmDto apm = new DictScheduleApmDto();
        apm.setQueues(queues);
        List<DictScheduleApmDto> dsaList = dictScheduleApmMapper.getCommonScheduleApm(apm);

        // 过滤掉无用的时段
        Iterator<DictScheduleApmDto> it = dsaList.iterator();
        while (it.hasNext()) {
            DictScheduleApmDto dsa = it.next();
            if (dsa.getDateStart() != null && dsa.getDateEnd() != null) {
                // 传入的开始日期
                String paramDate = dto.getStartDate();
                // 长周期
                if (dsa.getDateStart().length() == 5) {
                    paramDate = paramDate.substring(5);
                }
                // 在日期范围内
                if (paramDate.compareTo(dsa.getDateStart()) >= 0 && paramDate.compareTo(dsa.getDateEnd()) <= 0) {
                    continue;
                }
                if (dsa.getDateEnd().compareTo(dsa.getDateStart()) < 0
                        && paramDate.compareTo(dsa.getDateStart()) <= 0
                        && paramDate.compareTo(dsa.getDateEnd()) <= 0) {
                    continue;
                }
                if (dsa.getDateEnd().compareTo(dsa.getDateStart()) < 0
                        && paramDate.compareTo(dsa.getDateStart()) >= 0
                        && paramDate.compareTo(dsa.getDateEnd()) >= 0) {
                    continue;
                }
                it.remove();
            }
        }

        Map<String, String> mapDate = new HashMap<>();
        // 队列时段key(queueName=ApmFlag)   时段信息
        Map<String, TreeMap<String, Object>> apmFlagMap = new TreeMap<>();
        for (DictScheduleApmDto apmDto : dsaList) {
            String key = apmDto.getQueueName() + "=" + apmDto.getApmFlag();

            // 查询人员排班列表
            DictScheduleApmDutyDto queryDutyDto = new DictScheduleApmDutyDto();
            queryDutyDto.setStatus("1");
            queryDutyDto.setApmCode(apmDto.getApmCode());
            queryDutyDto.setStartDate(dto.getStartDate());
            queryDutyDto.setEndDate(dto.getEndDate());
            List<DictScheduleApmDuty> dutyList = dictScheduleApmDutyService.getDutyList(queryDutyDto);

            if (apmFlagMap.containsKey(key)) {
                Map<String, Object> apmMap = apmFlagMap.get(key);
                String scheduleApm = apmMap.get("scheduleApm") + "";
                String timeStart = apmMap.get("timeStart") + "";
                List<String> timeStartList = Arrays.asList(timeStart.split(","));
                if (!timeStartList.contains(apmDto.getTimeStart())) {
                    scheduleApm = apmMap.get("scheduleApm") + "," + apmDto.getScheduleApm();
                    apmMap.put("timeStart", timeStart + "," + apmDto.getTimeStart());
                    apmMap.put("scheduleApm", scheduleApm);
                }
                String apmCode = apmDto.getApmCode();
                if (apmMap.get("apmCode") != null) {
                    apmCode = apmMap.get("apmCode") + "," + apmDto.getApmCode();
                }
                apmMap.put("apmCode", apmCode);
                List<Map<String, Object>> staffList = (List<Map<String, Object>>) apmMap.get("staffs");
                List<Map<String, Object>> staffList2 = new ArrayList<>();
                if (CollectionUtils.isEmpty(dutyList)) {
                    continue;
                }
                for (DictScheduleApmDuty dutys : dutyList) {
                    if (mapDate.containsKey(key + dutys.getScheduleDate())) {
                        if (CollectionUtils.isEmpty(staffList)) {
                            continue;
                        }
                        for (Map<String, Object> staffMap : staffList) {
                            String dutyDate = (staffMap.get("dutyDate") != null) ? staffMap.get("dutyDate").toString() : "";
                            String staffName = (staffMap.get("staffName") != null) ? staffMap.get("staffName").toString() : "";
                            if (dutyDate.equals(dutys.getScheduleDate())) {
                                List<String> staffNameList = Arrays.asList(staffName.split(","));
                                if (!staffNameList.contains(dutys.getStaffName())) {
                                    staffName = staffName + "," + dutys.getStaffName();
                                    staffMap.put("staffName", staffName);
                                }
                            }
                        }
                    } else {
                        Map<String, Object> staffMap2 = new HashMap<String, Object>();
                        staffMap2.put("dutyDate", dutys.getScheduleDate());
                        staffMap2.put("staffName", dutys.getStaffName());
                        staffList2.add(staffMap2);
                        mapDate.put(key + dutys.getScheduleDate(), "");
                    }
                }
                staffList.addAll(staffList2);
                apmMap.put("staffs", staffList);
            } else {
                // 构建时段信息map  时段信息下面挂载人员排班列表
                TreeMap<String, Object> apmMap = new TreeMap<>();
                apmMap.put("apmFlag", apmDto.getApmFlag());
                apmMap.put("scheduleApm", apmDto.getScheduleApm());
                apmMap.put("timeStart", apmDto.getTimeStart());
                apmMap.put("apmCode", apmDto.getApmCode());

                // 人员列表
                List<Map<String,String>> staffList = new ArrayList<>();
                if (CollectionUtils.isNotEmpty(dutyList)) {
                    for (DictScheduleApmDuty duty : dutyList) {
                        Map<String, String> staffDateMap = new HashMap<>();
                        staffDateMap.put("dutyDate", duty.getScheduleDate());
                        staffDateMap.put("staffName", duty.getStaffName());
                        staffList.add(staffDateMap);
                        mapDate.put(key + duty.getScheduleDate(), "");
                    }
                    apmMap.put("staffs", staffList);
                }
                apmFlagMap.put(key, apmMap);
            }
        }
        // 按日期排序
        for (String key : apmFlagMap.keySet()) {
            //时段信息map  时段信息下面挂载人员排班列表
            TreeMap<String, Object> apmMap = apmFlagMap.get(key);
            // 人员信息
            List<Map<String, Object>> list = (List<Map<String, Object>>) apmMap.get("staffs");
            if (CollectionUtils.isNotEmpty(list)) {
                Collections.sort(list, new Comparator<Map<String, Object>>() {
                    @Override
                    public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                        String dutyDate1 = (o1.get("dutyDate") == null) ? "" : o1.get("dutyDate").toString();
                        String dutyDate2 = (o2.get("dutyDate") == null) ? "" : o2.get("dutyDate").toString();
                        return dutyDate1.compareTo(dutyDate2);
                    }
                });
            }
        }
        // 时段去掉，把时段都直接挂载到时段列表
        List<Map<String, Object>> listMap = new ArrayList<>();
        for (DictExamQueueDto queue : queues) {
            Map<String, Object> queueMap = new HashMap<>();
            List<Map<String, Object>> apmMaps = new ArrayList<>();
            for (String key : apmFlagMap.keySet()) {
                String keyName = key.split("=")[0];
                if (queue.getQueueName().equals(keyName)) {
                    // 时段信息
                    TreeMap<String, Object> apmMap = apmFlagMap.get(key);
                    apmMaps.add(apmMap);
                }
            }
            queueMap.put("queueName", queue.getQueueName());
            queueMap.put("dutys", apmMaps);
            listMap.add(queueMap);
        }
        return JsonResultUtil.success(listMap);
    }

    @Override
    public JsonResult insertDuty(DictScheduleApmDutyDto dto) {
        String status = (dto.getStatus() != null) ? dto.getStatus() : "1";
        List<DictScheduleApmDutyDto> dutyList = dto.getDutyList();
        for (DictScheduleApmDutyDto dsad : dutyList) {
            if (StringUtils.isBlank(dsad.getApmCode())) {
                return JsonResultUtil.failure("属性:[apmCode]不能为空");
            }
            dutyDelete(dsad);
            String[] split = dsad.getApmCode().split(",");
            for (String apmCode : split) {
                DictScheduleApmDuty duty = new DictScheduleApmDuty();
                duty.setApmCode(apmCode);
                duty.setScheduleDate(dsad.getScheduleDate());
                duty.setStaffName(dsad.getStaffName());
                duty.setStaffNo(dsad.getStaffNo());
                duty.setStatus(status);
                dictScheduleApmDutyService.insertSelective(duty);
            }
        }
        return JsonResultUtil.success("成功");
    }

    @Override
    public JsonResult dutyDelete(DictScheduleApmDutyDto dto) {
        DictScheduleApmDutyDto duty = new DictScheduleApmDutyDto();
        duty.setApmCodes(CommonUtil.split2List(dto.getApmCode()));
        duty.setScheduleDate(dto.getScheduleDate());
        boolean delete = dictScheduleApmDutyService.delete(duty);
        if (!delete) {
            return JsonResultUtil.failure("删除失败");
        }
        return JsonResultUtil.success("删除成功");
    }

    /**
     * 获取日期段内可用的时段列表
     * @param dto
     * @return
     */
    public List<DictScheduleApmDto> getEnableApmList(DictScheduleApmDutyDto dto){
        // 获取检查类别的可用队列
        DictExamQueueDto dictExamQueueDto = new DictExamQueueDto();
        dictExamQueueDto.setClassAttr(dto.getClassAttr());
        dictExamQueueDto.setExamClassList(CommonUtil.split2List(dto.getExamClass()));
        List<DictExamQueueDto> queues = dictExamQueueService.getQueueList(dictExamQueueDto);

        // 获取队列的时段列表
        DictScheduleApmDto apm = new DictScheduleApmDto();
        apm.setQueues(queues);
        List<DictScheduleApmDto> dsaList = dictScheduleApmMapper.getCommonScheduleApm(apm);

        // 过滤掉无用的时段
        Iterator<DictScheduleApmDto> it = dsaList.iterator();
        while (it.hasNext()) {
            DictScheduleApmDto dsa = it.next();
            if (dsa.getDateStart() != null && dsa.getDateEnd() != null) {
                // 传入的开始日期
                String paramDate = dto.getStartDate();
                // 长周期
                if (dsa.getDateStart().length() == 5) {
                    paramDate = paramDate.substring(5);
                }
                // 在日期范围内
                if (paramDate.compareTo(dsa.getDateStart()) >= 0 && paramDate.compareTo(dsa.getDateEnd()) <= 0) {
                    continue;
                }
                if (dsa.getDateEnd().compareTo(dsa.getDateStart()) < 0
                        && paramDate.compareTo(dsa.getDateStart()) <= 0
                        && paramDate.compareTo(dsa.getDateEnd()) <= 0) {
                    continue;
                }
                if (dsa.getDateEnd().compareTo(dsa.getDateStart()) < 0
                        && paramDate.compareTo(dsa.getDateStart()) >= 0
                        && paramDate.compareTo(dsa.getDateEnd()) >= 0) {
                    continue;
                }
                it.remove();
            }
        }

        return dsaList;
    }
}
